package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.ReportDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    /*
     * 根据传入的dto获取日期列表，返回日期集合
     * */
    private static List<LocalDate> getDates(ReportDTO dto) {
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate begin = dto.getBegin();
        LocalDate end = dto.getEnd();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    @Override
    public TurnoverReportVO turnoverStatistics(ReportDTO dto) {
        List<LocalDate> dateList = getDates(dto);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double trunover = orderMapper.sumByMap(map);
            trunover = trunover == null ? 0.0 : trunover;
            turnoverList.add(trunover);
        }

        return TurnoverReportVO.
                builder().
                dateList(StringUtils.join(dateList, ",")).
                turnoverList(StringUtils.join(turnoverList, ",")).
                build();
    }

    @Override
    public UserReportVO userStatistics(ReportDTO dto) {
        List<LocalDate> dateList = getDates(dto);
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end", endTime);
            Integer totalUser = userMapper.selectUser(map);
            //totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);

            map.put("begin", beginTime);
            Integer newUser = userMapper.selectUser(map);
            //newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
        }
        return UserReportVO.
                builder().
                dateList(StringUtils.join(dateList, ",")).
                newUserList(StringUtils.join(newUserList, ",")).
                totalUserList(StringUtils.join(totalUserList, ",")).
                build();
    }

    @Override
    public OrderReportVO ordersStatistics(ReportDTO dto) {
        List<LocalDate> dateList = getDates(dto);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end", endTime);
            map.put("begin", beginTime);
            Integer allCount = orderMapper.selectAllCount(map);
            orderCountList.add(allCount);
            totalOrderCount += allCount;
            map.put("status", Orders.COMPLETED);
            Integer trueCount = orderMapper.selectAllCount(map);
            validOrderCountList.add(trueCount);
            validOrderCount += trueCount;
        }

        double orderCompletionRate = totalOrderCount != 0 ? (double) validOrderCount / totalOrderCount : 0.0;

        return OrderReportVO.
                builder().
                dateList(StringUtils.join(dateList, ",")).//日期列表
                        orderCountList(StringUtils.join(orderCountList, ",")).//每日订单数
                        validOrderCountList(StringUtils.join(validOrderCountList, ",")).//每日有效订单数
                        totalOrderCount(totalOrderCount).//订单总数
                        validOrderCount(validOrderCount).//有效订单数
                        orderCompletionRate(orderCompletionRate). //订单完成率
                        build();
    }

    @Override
    public SalesTop10ReportVO top10(ReportDTO dto) {
        LocalDateTime begin = LocalDateTime.of(dto.getBegin(), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dto.getEnd(), LocalTime.MAX);
        List<GoodsSalesDTO> dtos = orderMapper.saleTop10(begin, end);
        List<String> nameList = dtos.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = dtos.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ",")).build();
    }

    @Override
    public void export(HttpServletResponse response) throws IOException {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //概览数据
        BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //读取模板
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //获取标签页
        XSSFSheet sheet1 = excel.getSheet("Sheet1");
        //填充概览数据
        sheet1.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
        XSSFRow row3 = sheet1.getRow(3);
        row3.getCell(2).setCellValue(vo.getTurnover());
        row3.getCell(4).setCellValue(vo.getOrderCompletionRate());
        row3.getCell(6).setCellValue(vo.getNewUsers());
        XSSFRow row4 = sheet1.getRow(4);
        row4.getCell(2).setCellValue(vo.getValidOrderCount());
        row4.getCell(4).setCellValue(vo.getUnitPrice());
        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date=begin.plusDays(i);
            BusinessDataVO vo1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(vo1.getTurnover());
            row.getCell(3).setCellValue(vo1.getValidOrderCount());
            row.getCell(4).setCellValue(vo1.getOrderCompletionRate());
            row.getCell(5).setCellValue(vo1.getUnitPrice());
            row.getCell(6).setCellValue(vo1.getNewUsers());
        }

        //保存并关闭资源
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.close();
        excel.close();
    }


}
